import prisma from '../lib/prisma';

interface TableInfo {
  tablename: string;
}

async function globalTeardown(): Promise<void> {
  try {
    await prisma.$connect();
    
    // 清理所有测试数据
    const tablenames = await prisma.$queryRaw<TableInfo[]>`
      SELECT tablename 
      FROM pg_tables
      WHERE schemaname='public'
    `;

    const tables = tablenames
      .map(({ tablename }: TableInfo) => tablename)
      .filter((name: string) => !name.includes('_prisma_'))
      .filter((name: string) => !name.includes('schema_migrations'));

    await prisma.$transaction([
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL DEFERRED'),
      ...tables.map((table: string) => 
        prisma.$executeRawUnsafe(`TRUNCATE TABLE "${table}" CASCADE`)
      ),
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL IMMEDIATE'),
    ]);
  } catch (error) {
    console.error('Test teardown failed:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

export default globalTeardown;
